package com.first.wchat;


import java.io.File;
import java.util.ArrayList;
import com.first.wchat.connect.udp.UDPConnectSevice;
import com.first.wchat.data.MSGDataManager;
import com.first.wchat.data.MSGDataManager.ImageMessageData;
import com.first.wchat.data.MSGDataManager.MessageData;
import com.first.wchat.data.WchatListener;
import com.wchat.network.Controller;
import com.wchat.network.device.SendTarget;
import com.wchat.util.Util;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ChatActivity extends Activity implements WchatListener{

	UDPConnectSevice mSevice;
	ListView mList;
	EditText mEditor;
	Button mSend;
	Button mFindImage;
	SendTarget mTarget;
	
	Uri mUri;

	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	
    	Intent intent = getIntent();
    	mTarget = (SendTarget) intent.getSerializableExtra("Target");
    	setContentView(R.layout.chat);

    	getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    	initView();
    	MSGDataManager.getInstance().addListener(this);
    }
    
    public void onStart()
    {
    	super.onStart();
    	
    }
    
    public void onDestroy()
    {
    	
    	MSGDataManager.getInstance().removeListener(this);
    	super.onDestroy();
    }
    
    
    protected void onActivityResult (int requestCode, int resultCode, Intent data) 
    {
    	
    	if(requestCode == 1 && resultCode == Activity.RESULT_OK && data!= null)
    	{
    		mUri = data.getData();
    		mEditor.setText(mUri.toString());
    	}
    }
    
    private void initView()
    {
    	mList = (ListView)findViewById(R.id.chat_history);
    	mEditor = (EditText)findViewById(R.id.inputTool);
    	mSend = (Button)findViewById(R.id.send);
    	mSend.setOnClickListener(new MyOnClickListener());
    	
    	mFindImage = (Button)findViewById(R.id.findImage);
    	mFindImage.setOnClickListener(new MyOnClickListener());
    	mList.setAdapter(new MsgAdapter(MSGDataManager.getInstance().getMessage(mTarget)));
    }

    
   class MyOnClickListener implements OnClickListener
    {

	   String mPath;
		public MyOnClickListener()
		{
			
		}
		public MyOnClickListener(String filePath)
		{
			mPath = filePath;
		}
		@Override
		public void onClick(View view) {
			
			if(R.id.send == view.getId())
			{
				String msg = mEditor.getEditableText().toString();
				if(mUri == null)
				{
					if(msg == null || msg== "")
					{
						Toast.makeText(ChatActivity.this, "can't send since no message!", Toast.LENGTH_SHORT).show();
						return;
					}
					
					MSGDataManager.getInstance().addMessage(mTarget, Controller.getInstance().getDeviceContext().getLocal(),msg,null);
					MainActivity.getUserAction().sendText(msg, mTarget);
				}
				else
				{
					String path = Util.getUriFilePath(ChatActivity.this, mUri);
					File imageFile = new File(path);
					MSGDataManager.getInstance().addMessage(mTarget, Controller.getInstance().getDeviceContext().getLocal(),Util.getScaleBitmap(imageFile),imageFile.getAbsolutePath());
					MainActivity.getUserAction().sendImage(imageFile, mTarget);
					mUri = null;
				}
				mEditor.clearComposingText();
				mEditor.setText("");
			}
			else if(R.id.findImage == view.getId())
			{
				Intent intent = new Intent();
				intent.setAction(android.content.Intent.ACTION_GET_CONTENT);
				intent.setType("image/*");
				ChatActivity.this.startActivityForResult(intent, 1);
			}
			else if(R.id.msg_ImageS == view.getId())
			{
				if(mPath.contains("/mnt/"))
					mPath = mPath.replace("/mnt/", "/");
				if(!mPath.startsWith("file://"))
					mPath = "file://"+mPath;
				Uri uri = Uri.parse(mPath);
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(uri, "image/*");
				ChatActivity.this.startActivity(intent);
			}
			
		}
    	
    }
   
   
   private class MsgAdapter extends BaseAdapter {

	   ArrayList<MessageData> msg;

		public MsgAdapter(ArrayList<MessageData> arrayList)
		{
			if(arrayList == null)
				msg = new ArrayList<MessageData>();
			else
				msg = arrayList;
		}
		
		public void add(MessageData md)
		{
			msg.add(md);
		}

		@Override
		public int getCount() {
			return msg.size();
		}

		@Override
		public Object getItem(int position) {
			return msg.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View contentView, ViewGroup parent) {
			
			LinearLayout layout = (LinearLayout) View.inflate(ChatActivity.this, R.layout.chat_item, null);
			ImageView icon = (ImageView)layout.findViewById(R.id.icon);
			icon.setImageResource(R.drawable.icon);
			MessageData message =  (MessageData)getItem(position);
			TextView name = (TextView)layout.findViewById(R.id.name);
			name.setText(message.getDevice().getAddress()+" : ");

			TextView msg = (TextView)layout.findViewById(R.id.msg);
			ImageView msg_image = (ImageView)layout.findViewById(R.id.msg_ImageS);
	    	
			if(message.isTextType())
			{
				msg_image.setVisibility(View.GONE);
				msg.setVisibility(View.VISIBLE);
				msg.setText((String)message.getMessage());
			}
			else
			{
				msg_image.setVisibility(View.VISIBLE);
				msg.setVisibility(View.GONE);
				msg_image.setOnClickListener(new MyOnClickListener(((ImageMessageData)message).getPath()));
				msg_image.setBackgroundDrawable(new BitmapDrawable((Bitmap)message.getMessage()));
			}
				
			return layout;
		}

	}


	@Override
	public void newMessage(SendTarget target, Object o) {
		initView();
	}

	@Override
	public void newMessage(SendTarget group, SendTarget target, Object o) {
		// TODO Auto-generated method stub
		
	}
	
}
